package com.android.djlmapp.activity.home;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.djlmapp.R;
import com.android.djlmapp.adapter.home.UploadImageAdapter;
import com.android.djlmapp.base.BaseActivity;
import com.android.djlmapp.listener.read.GetPhotoUrlListener;
import com.android.djlmapp.tools.global.ToastUtils;
import com.android.djlmapp.tools.read.GetPhotoUrlUtils;
import com.android.readcard.dialog.MyUsualyDialog;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class ChooseActivity extends BaseActivity {

    @BindView(R.id.grid_upload_pictures)
    GridView uploadGridView;
    @BindView(R.id.ll_top_back)
    LinearLayout llTopBack;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_top_jump)
    TextView tvTopJump;
    @BindView(R.id.iv_top_msg)
    ConstraintLayout ivTopMsg;
    @BindView(R.id.iv_top_set)
    ImageView ivTopSet;
    @BindView(R.id.iv_top_kf)
    ImageView ivTopKf;
    /**
     * 需要上传的图片路径 控制默认图片在最后面需要用LinkedList
     */
    private LinkedList<String> dataList = new LinkedList<String>();
    private UploadImageAdapter adapter;
    private String url_link;
    private String actionUrl;
    private MyUsualyDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose);
        ButterKnife.bind(this);
        initView();
        initData();
    }

    @Override
    protected void initView() {
        dialog = new MyUsualyDialog(ChooseActivity.this, R.layout.wait_item);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(false);

        Intent intt = getIntent();
        if (intt.getStringExtra("url_one") != null) {
            url_link = intt.getStringExtra("url_one").toString().substring(43, 54)
                    + intt.getStringExtra("url_one").toString().substring(57, 67);
        } else {
            url_link = intt.getStringExtra("url_two").toString().substring(47, 58)
                    + intt.getStringExtra("url_two").toString().substring(61, 75);
        }
    }

    @Override
    protected void initData() {
        llTopBack.setVisibility(View.VISIBLE);
        ivTopMsg.setVisibility(View.GONE);
        ivTopSet.setVisibility(View.GONE);
        ivTopKf.setVisibility(View.GONE);
        tvTopJump.setVisibility(View.VISIBLE);
        tvName.setText("选择照片");
        tvTopJump.setText("上传照片");

        dataList = new LinkedList<String>();
        dataList.addLast(null);// 初始化第一个添加按钮数据
        adapter = new UploadImageAdapter(ChooseActivity.this, dataList);

        uploadGridView.setAdapter(adapter);
        uploadGridView.setOnItemClickListener(mItemClick);
        uploadGridView.setOnItemLongClickListener(mItemLongClick);

    }

    @OnClick({R.id.tv_top_jump})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_top_jump:
                ChooseActivityPermissionsDispatcher.NeedsWithCheck(this);
                break;
        }
    }

    private void upLoadImg() {
        actionUrl = "https://boss.djlm.wang/" + "sale/card/upload.html?num=" + url_link;
        for (int i = 0; i < mapPic.size(); i++) {
            final int finalI = i + 1;
            GetPhotoUrlUtils.subChoosePhoto(actionUrl, mapPic.get(i + ""),
                    new GetPhotoUrlListener() {
                        @Override
                        public void backPhotoUrl(int backType, String photoUrl) {
                            if (backType == 1) {
                                Toast.makeText(ChooseActivity.this,
                                        "照片" + finalI + "上传成功", Toast.LENGTH_SHORT).show();
                                if (finalI == mapPic.size()) {
                                    if (dialog != null) {
                                        dialog.dismiss();
                                    }
                                }
                            } else {
                                Toast.makeText(ChooseActivity.this,
                                        "照片" + finalI + "上传失败，网络或服务器错误", Toast.LENGTH_SHORT).show();
                                if (dialog != null) {
                                    dialog.dismiss();
                                }
                            }
                        }
                    });
        }
    }

    private int selectPosition = 0;

    /**
     * 上传图片GridView Item单击监听
     */
    private OnItemClickListener mItemClick = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            if (parent.getItemAtPosition(position) == null) { // 添加图片
                selectPosition = position;
                takePhoto();
            }
        }
    };
    /**
     * 上传图片GridView Item长按监听
     */
    private OnItemLongClickListener mItemLongClick = new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view,
                                       int position, long id) {
            if (parent.getItemAtPosition(position) != null) { // 长按删除
                dataList.remove(parent.getItemAtPosition(position));
                mapPic.remove(position + "");
                adapter.update(dataList); // 刷新图片
            }
            return true;
        }
    };

    @Override
    public void takeSuccess(TResult result) {
        ArrayList<TImage> images = result.getImages();
        Log.e("项目异常", "------takeSuccess------" + images.size());
        Log.e("项目异常", "------getCompressPath------" + result.getImages().get(0).getCompressPath());
        Log.e("项目异常", "------getOriginalPath------" + images.get(0).getOriginalPath());

        showImg(images);
    }

    private HashMap<String, File> mapPic = new HashMap<>();

    private void showImg(final ArrayList<TImage> images) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                String compressPath = images.get(0).getCompressPath();
                if (compressPath != null && !TextUtils.isEmpty(compressPath)) {
                    Log.e("项目异常", "------showImg------" + compressPath);
                    File file = new File(compressPath);
                    dataList.addFirst(compressPath);
                    mapPic.put(selectPosition + "", file);
                    adapter.update(dataList); // 刷新图片
                }
            }
        });
    }

    @Override
    public void takeFail(TResult result, final String msg) {
        Log.e("项目异常takeSuccess", "------takeFail------" + msg);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtils.showShortToast(ChooseActivity.this, "拍照/压缩失败" + msg);
            }
        });
    }

    @Override
    public void takeCancel() {
        Log.e("项目异常", "------takeCancel------");
    }

    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void Needs() {
        if (mapPic.size() > 0) {
            dialog.show();
            upLoadImg();//提交
        } else {
            ToastUtils.showShortToast(ChooseActivity.this, "请先拍照");
        }

    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        ChooseActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void OnShowRationale(final PermissionRequest request) {
        request.proceed();
        isFirst = false;
    }

    @OnPermissionDenied({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void Denied() {
        if (isFirst) {
            return;
        }
        new AlertDialog.Builder(this)
                .setMessage("请开启应用的存储权限")
                .setCancelable(false)
                .setNegativeButton("确定", (dialog1, which) -> finish()).show();
    }

    @OnNeverAskAgain({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void AskAgain() {
        if (isFirst) {
            return;
        }
        new AlertDialog.Builder(this)
                .setMessage("请开启应用的存储权限")
                .setCancelable(false)
                .setNegativeButton("确定", (dialog1, which) -> finish()).show();
    }

    private boolean isFirst = true;
}
